<template>
  <div class="body">
    <div class="table_content">
      <!-- <div class="table_filtrate">
        <div class="tf_item">
          <el-button @click="loadTableData" type="primary" plain
            >搜索</el-button
          >
        </div>
      </div> -->

      <div class="table_operate">
        <el-button
          class="btn_add"
          type="primary"
          size="mini"
          @click="handleToGoCreate()"
          >添加</el-button
        >
      </div>

      <div class="table-card">
        <el-table
          class="table"
          :data="tableData.data"
          :row-class-name="tableRowClassName"
          v-loading="loading.table"
          :border="true"
          size="mini"
          show-summary
          :summary-method="$_App_getSummaries"
        >
          <el-table-column prop="weight" label="排序" width="50">
            <template slot-scope="scope">
              <el-link
                style="text-align: center"
                icon="el-icon-top"
                @click="tableUpdateTop(scope.row)"
              ></el-link>
            </template>
          </el-table-column>
          <el-table-column prop="logo" label="应用图标">
            <template slot-scope="scope">
              <img style="height: 30px; width: 30px" :src="scope.row.logo" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="应用名称"> </el-table-column>
          <el-table-column prop="cooperative_price" label="合作价格">
          </el-table-column>
          <!-- <el-table-column prop="" label="余额"> </el-table-column> -->
          <el-table-column prop="" label="定时上下线" width="120">
            <template slot-scope="scope">
              {{ scope.row.today_start_time + "至" + scope.row.today_end_time }}
            </template>
          </el-table-column>
          <el-table-column prop="balance" label="余额"> </el-table-column>
          <el-table-column label="限制访问"> </el-table-column>
          <el-table-column label="联登状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.federated_login"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                disabled
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="" label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                @change="tableUpdateItem(scope.row, 'status')"
                active-value="normal"
                inactive-value="stop"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!-- <el-link
              class="handle"
              type="warning"
              v-show="scope.row.status == 'stop'"
              @click="handleTableRegain(scope.$index, scope.row)"
              >恢复</el-link
            > -->
              <el-link
                class="handle"
                type="primary"
                @click="handleTableEdit(scope.$index, scope.row)"
                >编辑</el-link
              >
              <el-link
                class="handle"
                type="primary"
                @click="
                  handleTableRecharge(scope.$index, scope.row, 'recharge')
                "
                >充值</el-link
              >
              <el-link
                class="handle"
                type="primary"
                @click="handleTableRecharge(scope.$index, scope.row, 'expense')"
                >退款</el-link
              >
              <!-- <el-link
              class="handle"
              type="danger"
              @click="handleTableDelete(scope.$index, scope.row)"
              >删除</el-link
            > -->
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          @size-change="handleTableSizeChange"
          @current-change="handleTableCurrentChange"
          :current-page="currentPage4"
          :page-sizes="$pageSize"
          :page-size="tableParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {
  apiAdvertisingListpage,
  apiAdvertisingUpdatesingle,
} from "@/api/apiCommon";
import { paramsDeleteNull } from "@/utils/common";
import {
  getUploadingImgUrl,
  getUploadingVideoUrl,
  getImgUrl,
} from "@/api/uploading";
export default {
  name: "Index",
  data() {
    return {
      tableParams: {
        page: 1,
        size: 15,
      },
      tableData: {
        current_page: 1,
        data: [],
        last_page: 1,
        per_page: "15",
        total: 0,
      },
      currentPage4: 1,
      business_select: [],
      organization_select: [],
      fromViewCofing: {
        input_width: "120px",
        label_width: "120px",
      },
      loading: {
        loadingCount: 0,
        dialog_create: false,
        table: false,
        form: false,
      },
    };
  },
  created() {
    this.loadTableData();
  },
  methods: {
    // 列表请求
    loadTableData(is_initpage = true) {
      const _this = this;
      if (is_initpage) {
        _this.tableParams.page = 1;
      }
      _this.loading_start("table");
      var tableParamsData = { ..._this.tableParams };
      apiAdvertisingListpage(tableParamsData)
        .then((response) => {
          var tableData = response.data.datalist;
          var data = tableData.data;
          for (var i = 0; i < data.length; i++) {
            data[i]["logo"] = getImgUrl(data[i]["logo"]);
          }
          tableData.data = data;
          _this.tableData = tableData;
          _this.loading_end("table");
        })
        .catch(function (result) {
          _this.$message.error(result.msg);
          _this.tableData.data = null;
        });
    },
    // 页面跳转
    handleToGoCreate() {
      this.$router.push({ path: "/advertising/create", query: { id: 0 } });
    },
    // 表格行状态
    tableRowClassName({ row, rowIndex }) {
      if (row["status"] == "stop") {
        return "discard-row";
      }
    },
    // 表格 充值/退款
    handleTableRecharge(index, row, transaction_type = "recharge") {
      var advertising_name = row.name;
      var path = "/advertising/recharge";
      if (transaction_type == "expense") {
        path = "/advertising/expense";
      }
      this.$router.push({
        path: path,
        query: {
          id: row.id,
          transaction_type: transaction_type,
          advertising_name: advertising_name,
        },
      });
    },
    // 表格操作
    handleTableEdit(index, row) {
      this.$router.push({ path: "/advertising/update", query: { id: row.id } });
    },
    // 表格恢复
    handleTableRegain(index, row) {
      var _this = this;
      var params = {
        id: row.id,
        status: "normal",
      };
      _this.loading_start("table");
      apiProductUpdatePart(params).then((response) => {
        _this.loading_end("table");
        _this.loadTableData();
      });
    },
    // 表格删除
    handleTableDelete(index, row) {
      const _this = this;
      _this.loading_start("table");
      apiProductDelete({
        id: row.id,
      }).then((response) => {
        this.$message({
          message: response.msg,
          type: "success",
        });
        _this.loading_end("table");
        _this.loadTableData();
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总价";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += " 元";
        } else {
          sums[index] = "N/A";
        }
      });

      return sums;
    },
    // 数量改变
    handleTableSizeChange(val) {
      this.tableParams.size = val;
      this.loadTableData(false);
    },
    // 页数改变
    handleTableCurrentChange(val) {
      this.tableParams.page = val;
      this.loadTableData(false);
    },
    // 表格置顶
    tableUpdateTop(item) {
      var _this = this;
      var params = {
        id: item.id,
        weight: "1",
      };
      _this.loading_start("table");
      apiAdvertisingUpdatesingle(params).then((response) => {
        _this.loading_end("table");
        _this.loadTableData();
      });
    },

    // 部分状态改变
    tableUpdateItem(item, key) {
      var _this = this;
      var weight = _this.tableData.total;
      var params = {
        id: item.id,
      };
      params["id"] = item.id;
      params[key] = item[key];

      this.$confirm("是否更改状态", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          _this.loading_start("table");
          apiAdvertisingUpdatesingle(params).then((response) => {
            _this.loading_end("table");
            _this.loadTableData();
          });
        })
        .catch(() => {
          _this.loadTableData();
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 加载开始...
    loading_start(keys) {
      const _this = this;
      if (Array.isArray(keys)) {
        keys.forEach((key) => {
          _this.loading[key] = true;
          setTimeout(() => {
            _this.loading_end(key);
          }, 5000);
        });
      } else {
        _this.loading[keys] = true;
        setTimeout(() => {
          _this.loading_end(keys);
        }, 5000);
      }
    },
    // 加载结束...
    loading_end(keys) {
      const _this = this;
      const keyArray = Array.isArray(keys) ? keys : [keys];
      // 遍历每一个key并设置加载状态，同时减少等待计数
      keyArray.forEach((key) => {
        if (key && _this.loading[key]) {
          // 确保key有效且已加载
          _this.loading[key] = false;
          _this.loading.loadingCount = Math.max(
            0,
            _this.loading.loadingCount - 1
          ); // 确保计数不低于 0
        }
      });
    },
  },
};
</script>

<style lang="scss"></style>